<template>
  <div class="approval-operation">
    <!-- 审批结果和审批意见（仅在任务处理模式显示） -->
    <div v-if="!isStartMode" class="approval-basic-section">
      <h4 class="section-title">审批基本信息</h4>
      <el-form :model="approvalForm" ref="approvalFormRef" :rules="approvalRules" label-width="100px">
        <el-form-item label="审批结果" prop="approvalResult">
          <el-radio-group v-model="approvalForm.approvalResult" @change="handleApprovalResultChange">
            <el-radio label="PASS">通过</el-radio>
            <el-radio label="REJECT">拒绝</el-radio>
            <el-radio label="TRANSFER">转办</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审批意见" prop="approvalOpinion">
          <el-input
            v-model="approvalForm.approvalOpinion"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 转办人员选择 -->
    <div v-if="showTransferConfig" class="transfer-config-section">
      <h4 class="section-title">转办人员选择</h4>
      <el-form :model="transferForm" ref="transferFormRef" :rules="transferRules" label-width="100px">
        <el-form-item label="转办人员" prop="transferAssignee">
          <div class="transfer-assignee-selector">
            <el-input
              v-model="transferAssigneeName"
              placeholder="请选择转办人员"
              readonly
              style="width: 300px"
            >
              <template #append>
                <el-button @click="showTransferSelector">
                  <Icon icon="ant-design:user-outlined" />
                  选择人员
                </el-button>
              </template>
            </el-input>
            <el-button 
              v-if="transferAssignee" 
              type="danger" 
              size="small" 
              @click="clearTransferAssignee"
              style="margin-left: 10px"
            >
              清空
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 下一节点人员配置 -->
    <div v-if="showNextNodeConfig" class="next-node-config-section">
      <h4 class="section-title">下一节点人员配置</h4>
      <div class="config-content">
        <!-- 多节点选择 -->
        <div v-if="nextNodes.length > 1" class="node-selection">
          <h5 class="subsection-title">选择下一节点</h5>
          <el-radio-group v-model="selectedNextNode" @change="handleNextNodeChange">
            <el-radio 
              v-for="node in nextNodes" 
              :key="node.id || node.nodeId"
              :label="node.id || node.nodeId"
              :disabled="node.type === 'endEvent' || node.nodeType === 'EndEvent'"
            >
              {{ node.name || node.nodeName }} ({{ getNodeTypeText(node.type || node.nodeType) }})
            </el-radio>
          </el-radio-group>
        </div>
        
        <!-- 节点配置 -->
        <div v-for="node in activeNextNodes" :key="node.id || node.nodeId" class="node-config">
          <h5 class="subsection-title">{{ node.name || node.nodeName }} ({{ getNodeTypeText(node.type || node.nodeType) }})</h5>
          
          <!-- 用户任务节点配置 -->
          <div v-if="(node.type === 'userTask' || node.nodeType === 'UserTask' || node.nodeType === 'USER_TASK')" class="user-task-config">
            <!-- 处理人员配置（包含抄送配置） -->
            <PersonnelConfigDisplay
              title="处理人员"
              v-model="node.assignees"
              :cc-model-value="node.ccAssignees"
              :notification-methods="node.notificationMethodsArray"
              :default-handler-collapsed="true"
              :default-cc-collapsed="true"
              config-type="handler"
              :personnel-edit-permission="getNodeEditPermission(node)"
              :original-personnel="node.handlers || []"
              :original-cc-personnel="node.ccUsers || []"
              :original-notification-methods="node.notificationMethods || 'system'"
              @change="onNodeAssigneesChange(node)"
              @personnel-updated="(personnel) => updateNodePersonnel(node, personnel)"
              @view-detail="viewPersonnelDetail"
              @update:cc-model-value="(ccAssignees) => onNodeCcAssigneesChange(node, ccAssignees)"
              @cc-personnel-updated="(personnel) => updateNodeCcPersonnel(node, personnel)"
              @notification-methods-change="(methods) => onNotificationMethodsChange(node, methods)"
              @handler-config-collapsed-change="(collapsed) => onHandlerConfigCollapsedChange(node, collapsed)"
              @cc-config-collapsed-change="(collapsed) => onCcConfigCollapsedChange(node, collapsed)"
            />
          </div>
          
          <!-- 网关节点配置 -->
          <div v-if="(node.type && node.type.includes('Gateway')) || (node.nodeType && node.nodeType.includes('GATEWAY'))" class="gateway-config">
            <div class="gateway-info">
              <el-alert
                title="网关节点"
                :description="`${node.name || node.nodeName} 是${getNodeTypeText(node.type || node.nodeType)}，系统将根据条件自动选择下一节点`"
                type="info"
                show-icon
                :closable="false"
              />
            </div>
            
            <!-- 网关分支信息 -->
            <div v-if="node.gatewayBranches && node.gatewayBranches.length > 0" class="gateway-branches">
              <h6 class="sub-subsection-title">分支信息</h6>
              <div class="branch-list">
                <div v-for="branch in node.gatewayBranches" :key="branch.flowId" class="branch-item">
                  <div class="branch-header">
                    <span class="branch-name">{{ branch.flowName || branch.flowId }}</span>
                    <el-tag 
                      :type="branch.conditionMet ? 'success' : 'info'"
                      size="small"
                    >
                      {{ branch.conditionMet ? '条件满足' : '条件不满足' }}
                    </el-tag>
                  </div>
                  
                  <div class="branch-details">
                    <div class="branch-target">
                      <strong>目标节点:</strong> {{ branch.targetNodeName || branch.targetNodeId }}
                      <el-tag size="small" type="primary">{{ getNodeTypeText(branch.targetNodeType) }}</el-tag>
                    </div>
                    
                    <div v-if="branch.conditionExpression" class="branch-condition">
                      <strong>条件:</strong> {{ branch.conditionExpression }}
                    </div>
                    
                    <!-- 目标节点详细信息 -->
                    <div v-if="branch.targetNodeInfo" class="target-node-info">
                      <div class="target-node-description">
                        <strong>节点描述:</strong> {{ branch.targetNodeInfo.description }}
                      </div>
                      
                      <!-- 如果是用户任务，显示处理人员配置 -->
                      <div v-if="branch.targetNodeInfo.nodeType === 'USER_TASK'" class="target-handlers">
                        <PersonnelConfigDisplay
                          title="处理人员"
                          :model-value="convertHandlersToAssigneesForBranch(branch.targetNodeInfo.handlers || [])"
                          :cc-model-value="convertHandlersToAssigneesForBranch(branch.targetNodeInfo.ccHandlers || [])"
                          :notification-methods="branch.targetNodeInfo.notificationMethodsArray || ['system']"
                          :default-handler-collapsed="true"
                          :default-cc-collapsed="true"
                          config-type="handler"
                          @update:model-value="(assignees) => updateBranchHandlers(branch, assignees)"
                          @personnel-updated="(personnel) => updateBranchPersonnel(branch, personnel)"
                          @view-detail="viewPersonnelDetail"
                          @update:cc-model-value="(ccAssignees) => updateBranchCcHandlers(branch, ccAssignees)"
                          @cc-personnel-updated="(personnel) => updateBranchCcPersonnel(branch, personnel)"
                          @notification-methods-change="(methods) => updateBranchNotificationMethods(branch, methods)"
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 结束节点配置 -->
          <div v-if="(node.type === 'endEvent' || node.nodeType === 'EndEvent' || node.nodeType === 'END_EVENT')" class="end-node-config">
            <div class="end-node-info">
              <el-alert
                title="结束节点"
                description="流程将在该节点结束"
                type="success"
                show-icon
                :closable="false"
              />
            </div>
          </div>
          
          <!-- 服务任务节点配置 -->
          <div v-if="(node.type === 'serviceTask' || node.nodeType === 'ServiceTask' || node.nodeType === 'SERVICE_TASK')" class="service-task-config">
            <div class="service-task-info">
              <el-alert
                title="服务任务"
                :description="`${node.name || node.nodeName} 是服务任务，系统将自动执行`"
                type="warning"
                show-icon
                :closable="false"
              />
            </div>
          </div>
          
          <!-- 脚本任务节点配置 -->
          <div v-if="(node.type === 'scriptTask' || node.nodeType === 'ScriptTask' || node.nodeType === 'SCRIPT_TASK')" class="script-task-config">
            <div class="script-task-info">
              <el-alert
                title="脚本任务"
                :description="`${node.name || node.nodeName} 是脚本任务，系统将自动执行脚本`"
                type="warning"
                show-icon
                :closable="false"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 表单数据预览 -->
    <div v-if="showFormDataPreview" class="form-data-preview-section">
      <h4 class="section-title">表单数据预览</h4>
      <div class="config-content">
        <el-alert
          title="可用变量"
          description="以下变量可用于条件表达式中"
          type="info"
          show-icon
          :closable="false"
          style="margin-bottom: 15px;"
        />
        <div class="form-data-preview">
          <pre>{{ JSON.stringify(formDataPreview, null, 2) }}</pre>
        </div>
      </div>
    </div>
    
    <!-- 表单数据预览按钮 -->
    <div class="form-data-preview-button">
      <el-button 
        type="info" 
        size="small"
        @click="toggleFormDataPreview"
      >
        {{ showFormDataPreview ? '隐藏' : '显示' }}表单数据
      </el-button>
    </div>
    
    <!-- 提交按钮 -->
    <div class="submit-section">
      <el-button 
        type="primary" 
        size="large"
        @click="submitApproval"
        :loading="submitting"
        :disabled="!canSubmit"
      >
        {{ isStartMode ? '发起流程' : '提交审核' }}
      </el-button>
      <el-button 
        size="large"
        @click="resetForm"
      >
        重置
      </el-button>
    </div>
  </div>
  
  <!-- 转办人员选择器弹窗 -->
  <SelectorModal
    v-model:visible="transferSelectorVisible"
    type="user"
    :multiple="false"
    :selectedList="transferAssignee ? [{ id: transferAssignee, name: transferAssigneeName }] : []"
    @update:selectedList="handleTransferAssigneeSelect"
  />
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import AssigneeConfig from './AssigneeConfig.vue'
import SimplePersonnelList from './SimplePersonnelList.vue'
import PersonnelConfigDisplay from './PersonnelConfigDisplay.vue'
import { getGatewayConditions as calculateGatewayConditions } from '../utils/gatewayConditionCalculator'
import SelectorModal from '../../Selector/SelectorModal.vue'
import Icon from '@/components/Icon/Icon.vue'
import { getCurrentTaskNodeConfig } from '@/api/workflow/process.api'

// 引入统一的夜间模式样式
import '../styles/dark-theme.css'

const props = defineProps({
  processData: {
    type: Object,
    default: null
  },
  taskData: {
    type: Object,
    default: null
  },
  graphData: {
    type: Object,
    default: null
  },
  isStartMode: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: null
  },
  nextNodes: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits([
  'approval-action',
  'start-process',
  'personnel-updated',
  'view-personnel-detail'
])

// 计算属性
const formSchema = computed(() => {
  const schema = props.formData?.formSchema || props.formData?.formDetail?.formSchema
  
  // 如果schema是字符串，尝试解析为对象
  if (typeof schema === 'string') {
    try {
      const parsedSchema = JSON.parse(schema)
      return parsedSchema
    } catch (error) {
      return null
    }
  }
  
  // 如果已经是对象，直接返回
  if (schema && typeof schema === 'object') {
    return schema
  }
  
  return null
})

// 处理审批操作
const handleApprovalAction = (action, data) => {
  emit('approval-action', action, data)
}

// 提交审批
const submitApproval = async () => {
  if (submitting.value) {
    return
  }
  
  try {
    submitting.value = true
    
    // 如果是发起流程模式
    if (props.isStartMode) {
      // 始终获取人员配置并传递
      const assigneeConfig = getAssigneeConfig()
      
      // 调用父组件的方法发起流程
      emit('start-process', {
        formData: formData.value,
        assigneeConfig: assigneeConfig // 始终传递
      })
      
      return
    }
    
    // 任务处理模式：需要验证审批意见
    // 表单验证
    if (!approvalForm.value.approvalResult) {
      ElMessage.error('请选择审批结果')
      return
    }
    
    if (!approvalForm.value.approvalOpinion || approvalForm.value.approvalOpinion.trim() === '') {
      ElMessage.error('请填写审批意见')
      return
    }
    
    // 如果是转办，验证转办人员
    if (approvalForm.value.approvalResult === 'TRANSFER') {
      if (!transferAssignee.value) {
        ElMessage.error('请选择转办人员')
        return
      }
    }
    
    // 验证表单
    const isValid = await validateForm()
    if (!isValid) {
      ElMessage.error('请检查表单信息')
      return
    }
    
    // 验证审批通过时的下一节点配置
    if (approvalForm.value.approvalResult === 'PASS') {
      if (activeNextNodes.value.length === 0) {
        ElMessage.error('请配置下一节点人员')
        return
      }
      
      // 检查用户任务节点是否配置了处理人员
      const userTaskNodes = activeNextNodes.value.filter(node => 
        (node.type === 'userTask' || node.nodeType === 'UserTask' || node.nodeType === 'USER_TASK')
      )
      
      for (const node of userTaskNodes) {
        if (!node.convertedPersonnel || node.convertedPersonnel.length === 0) {
          ElMessage.error(`请为节点"${node.name || node.nodeName}"配置处理人员`)
          return
        }
      }
    }
    
    // 验证转办时的人员选择
    if (approvalForm.value.approvalResult === 'TRANSFER') {
      if (!transferAssignee.value) {
        ElMessage.error('请选择转办人员')
        return
      }
    }
    
    const approvalData = getApprovalData()
    
    // 只通过事件通知父组件处理，不直接调用后端API
    emit('approval-action', 'submit', approvalData)
  } catch (error) {
    ElMessage.error(props.isStartMode ? '发起流程失败' : '提交审批失败')
  } finally {
    submitting.value = false
  }
}

// 表单相关
const approvalFormRef = ref()

// 审批表单数据
const approvalForm = ref({
  approvalResult: 'PASS',
  approvalOpinion: ''
})

// 监听发起流程模式变化，设置合适的默认值
watch(() => props.isStartMode, (isStartMode) => {
  if (isStartMode) {
    // 发起流程模式：设置默认值，不需要审批意见
    approvalForm.value = {
      approvalResult: 'PASS',
      approvalOpinion: '发起流程'
    }
  } else {
    // 任务处理模式：重置为默认值
    approvalForm.value = {
      approvalResult: 'PASS',
      approvalOpinion: ''
    }
  }
}, { immediate: true })

// 表单验证规则
const approvalRules = computed(() => {
  if (props.isStartMode) {
    // 发起流程模式：不需要验证审批意见
    return {
      approvalResult: [
        { required: true, message: '请选择审批结果', trigger: 'change' }
      ]
    }
  } else {
    // 任务处理模式：需要验证审批意见
    return {
      approvalResult: [
        { required: true, message: '请选择审批结果', trigger: 'change' }
      ],
      approvalOpinion: [
        { required: true, message: '请输入审批意见', trigger: 'blur' }
      ]
    }
  }
})

// 转办表单相关
const transferFormRef = ref()
const transferForm = ref({
  transferAssignee: ''
})
const transferRules = {
  transferAssignee: [
    { required: true, message: '请选择转办人员', trigger: 'change' }
  ]
}

// 下一节点相关
const nextNodes = ref([])
const selectedNextNode = ref('')
const activeNextNodes = ref([])

// 防止循环更新的标志
const isUpdatingNodes = ref(false)

// 表单数据预览
const showFormDataPreview = ref(false)
const formDataPreview = ref({})

// 提交状态
const submitting = ref(false)

// 将handlers格式转换为assignees格式
const convertHandlersToAssignees = (handlers) => {
  if (!handlers || !Array.isArray(handlers)) {
    return []
  }
  
  // 按类型分组
  const groupedByType = {}
  handlers.forEach(handler => {
    // 处理不同的数据格式
    let type = handler.type
    let id = handler.id
    let name = handler.name || handler.nickName
    let account = handler.account || handler.userName
    
    // 如果没有type字段，默认为user
    if (!type) {
      type = 'user'
    }
    
    if (!groupedByType[type]) {
      groupedByType[type] = []
    }
    
    // 根据类型转换数据格式
    let convertedHandler = {}
    
    if (type === 'user') {
      // 用户类型：需要 nickName 和 userName 字段
      convertedHandler = {
        id: id,
        nickName: name, // 使用 name 或 nickName
        userName: account, // 使用 account 或 userName
        avatar: handler.avatar || '' // 如果有头像字段
      }
    } else if (type === 'role') {
      // 角色类型：需要 name 和 code 字段
      convertedHandler = {
        id: id,
        name: name,
        code: account // 使用 account 或 userName 作为 code
      }
    } else if (type === 'dept') {
      // 部门类型：需要 name 和 code 字段
      convertedHandler = {
        id: id,
        name: name,
        code: account // 使用 account 或 userName 作为 code
      }
    } else if (type === 'post') {
      // 岗位类型：需要 name 和 code 字段
      convertedHandler = {
        id: id,
        name: name,
        code: account // 使用 account 或 userName 作为 code
      }
    } else {
      // 其他类型：保持原样
      convertedHandler = {
        id: id,
        name: name,
        code: account
      }
    }
    
    groupedByType[type].push(convertedHandler)
  })
  
  // 转换为assignees格式
  const assignees = []
  Object.keys(groupedByType).forEach(type => {
    assignees.push({
      type: type,
      value: groupedByType[type]
    })
  })
  
  return assignees
}

// 将通知方式字符串转换为数组
const convertNotificationMethodsToArray = (notificationMethods) => {
  if (!notificationMethods) {
    return ['system']
  }
  
  if (typeof notificationMethods === 'string') {
    return notificationMethods.split(',').filter(method => method.trim())
  } else if (Array.isArray(notificationMethods)) {
    return [...notificationMethods]
  }
  
  return ['system']
}

// 监听props中的nextNodes变化
watch(() => props.nextNodes, (newNextNodes) => {
  // 添加防护措施，防止重复触发
  if (isUpdatingNodes.value) {
    return
  }
  
  if (newNextNodes && newNextNodes.length > 0) {
    // 对下一节点数据进行去重处理
    const uniqueNodes = []
    const seenIds = new Set()
    
    newNextNodes.forEach(node => {
      const nodeId = node.id || node.nodeId
      if (nodeId && !seenIds.has(nodeId)) {
        seenIds.add(nodeId)
        
        // 将handlers数据转换为assignees格式
        const assignees = convertHandlersToAssignees(node.handlers || [])
        
        // 将ccUsers数据转换为assignees格式
        const ccAssignees = convertHandlersToAssignees(node.ccUsers || [])
        
        // 处理通知方式
        const notificationMethodsArray = convertNotificationMethodsToArray(node.notificationMethods)
        
        uniqueNodes.push({
          ...node,
          id: nodeId,
          name: node.name || node.nodeName || '未知节点',
          type: node.type || node.nodeType || 'unknown',
          handlers: node.handlers || [],
          assignees: assignees, // 转换后的assignees格式
          ccUsers: node.ccUsers || [],
          ccAssignees: ccAssignees, // 转换后的抄送assignees格式
          notificationMethods: node.notificationMethods || 'system',
          notificationMethodsArray: notificationMethodsArray, // 转换后的通知方式数组
          handlerType: node.handlerType || 'user',
          convertedPersonnel: node.handlers || [], // 直接使用handlers作为转换后的人员列表
          // 设置默认的展开状态（收起状态）
          handlerConfigCollapsed: true,
          ccConfigCollapsed: true
        })
      }
    })
    
    nextNodes.value = uniqueNodes
    
    // 更新活跃节点，但不触发watch
    updateActiveNextNodesSilently()
    
    // 延迟更新网关条件状态，避免在响应式更新过程中修改数据
    setTimeout(() => {
      updateGatewayConditions()
    }, 0)
  } else {
    nextNodes.value = []
    activeNextNodes.value = []
  }
}, { immediate: true, deep: true })

// 静默更新活跃节点，不触发watch
const updateActiveNextNodesSilently = () => {
  if (isUpdatingNodes.value) {
    return
  }
  isUpdatingNodes.value = true
  
  if (selectedNextNode.value) {
    const selectedNode = nextNodes.value.find(node => 
      (node.id || node.nodeId) === selectedNextNode.value
    )
    if (selectedNode) {
      activeNextNodes.value = [selectedNode]
    }
  } else {
    activeNextNodes.value = [...nextNodes.value]
  }
  isUpdatingNodes.value = false
}

// 更新活跃的下一节点列表（用于用户交互）
const updateActiveNextNodes = () => {
  updateActiveNextNodesSilently()
}

// 移除所有可能导致循环的watch监听器

// 计算属性
const showNextNodeConfig = computed(() => {
  // 在拒绝和转办时不显示下一节点配置
  if (!props.isStartMode && approvalForm.value.approvalResult === 'REJECT') {
    return false
  }
  if (!props.isStartMode && approvalForm.value.approvalResult === 'TRANSFER') {
    return false
  }
  // 其他情况显示下一节点配置
  return nextNodes.value.length > 0
})

// 转办人员选择相关
const showTransferConfig = computed(() => {
  return !props.isStartMode && approvalForm.value.approvalResult === 'TRANSFER'
})

const transferAssignee = ref('')
const transferAssigneeName = ref('')
const transferSelectorVisible = ref(false)

const canSubmit = computed(() => {
  if (props.isStartMode) {
    // 发起模式：只要有下一节点配置就可以提交
    return activeNextNodes.value.length > 0
  } else {
    // 任务处理模式：原有的验证逻辑
    return approvalForm.value.approvalResult !== 'PASS' || 
           (approvalForm.value.approvalResult === 'PASS' && activeNextNodes.value.length > 0);
  }
})

// 获取节点类型文本
const getNodeTypeText = (nodeType) => {
  const typeMap = {
    'startEvent': '开始事件',
    'endEvent': '结束事件',
    'userTask': '用户任务',
    'serviceTask': '服务任务',
    'scriptTask': '脚本任务',
    'exclusiveGateway': '排他网关',
    'parallelGateway': '并行网关',
    'inclusiveGateway': '包容网关',
    'subProcess': '子流程',
    'callActivity': '调用活动',
    'start': '开始事件',
    'end': '结束事件',
    'task': '任务',
    'gateway': '网关',
    'USER_TASK': '用户任务',
    'SERVICE_TASK': '服务任务',
    'SCRIPT_TASK': '脚本任务',
    'START_EVENT': '开始事件',
    'END_EVENT': '结束事件',
    'event': '事件'
  }
  return typeMap[nodeType] || nodeType
}

// 获取节点编辑权限
const getNodeEditPermission = (node) => {
  // 完全依赖 getNextNodes 返回的配置
  // 从节点的 nodeConfig.advanced 中获取权限配置
  let nodePermission = 'full' // 默认值
  
  if (node.nodeConfig && node.nodeConfig.advanced && node.nodeConfig.advanced.personnelEditPermission) {
    nodePermission = node.nodeConfig.advanced.personnelEditPermission
  }
  
  // 检查是否为网关节点下的节点
  const isGatewayChildNode = node.parentNodeType && node.parentNodeType.includes('Gateway')
  
  // 如果是网关节点下的节点，默认允许编辑（除非明确设置为 disabled）
  if (isGatewayChildNode && nodePermission !== 'disabled') {
    return 'full'
  }
  
  return nodePermission
}

// 获取当前任务节点的配置信息
const fetchCurrentTaskNodeConfigData = async (taskId) => {
  try {
    const response = await getCurrentTaskNodeConfig(taskId)
    if (response && response.data) {
      return response.data
    }
    return null
  } catch (error) {
    console.error('获取当前任务节点配置失败:', error)
    return null
  }
}

// 当前任务节点配置
const currentTaskNodeConfig = ref(null)

// 在组件挂载时获取当前任务节点配置
onMounted(async () => {
  if (props.taskData && props.taskData.taskId) {
    const config = await fetchCurrentTaskNodeConfigData(props.taskData.taskId)
    if (config) {
      currentTaskNodeConfig.value = config
      console.log('获取到当前任务节点配置:', config)
    }
  }
})

// 获取处理人员类型文本
const getHandlerTypeText = (type) => {
  const typeMap = {
    'user': '用户',
    'dept': '部门',
    'role': '角色',
    'post': '岗位'
  }
  return typeMap[type] || type
}

// 获取人员显示名称
const getDisplayName = (user) => {
  if (!user) return '未知用户'
  
  // 参考UserSelector.vue的字段名，优先使用nickName
  const name = user.nickName || user.nickname || user.name || user.realName || user.displayName || user.userName
  if (name) return name
  
  // 如果都没有，返回用户ID或用户名
  return user.id || user.userId || user.username || user.userName || '未知用户'
}

// 移除数据加载相关的方法，只保留审批操作功能
// 移除 loadNextNodes, loadAssigneeConfig 等方法
// 保留 handleApprovalResultChange, handleNextNodeChange, showHandlerSelector 等交互方法

// 处理审批结果变化
const handleApprovalResultChange = (result) => {
  // 根据审批结果调整下一节点配置的显示和审批意见
  if (result === 'REJECT') {
    // 拒绝时不需要配置下一节点，设置默认拒绝意见
    approvalForm.value.approvalOpinion = '审批不通过，流程终止'
  } else if (result === 'TRANSFER') {
    // 转办时设置默认转办意见
    approvalForm.value.approvalOpinion = '转办给相关人员处理'
  } else if (result === 'PASS') {
    // 通过时设置默认通过意见
    approvalForm.value.approvalOpinion = '审批通过，流程继续'
  }
}

// 处理下一节点变化
const handleNextNodeChange = (nodeId) => {
  selectedNextNode.value = nodeId
  // 更新活跃的下一节点列表
  updateActiveNextNodes()
}

// 移除处理人员
const removeHandler = (nodeId, handler) => {
  const targetNode = activeNextNodes.value.find(node => 
    (node.id || node.nodeId) === nodeId
  )
  if (targetNode && targetNode.handlers) {
    const index = targetNode.handlers.findIndex(h => h.id === handler.id)
    if (index > -1) {
      targetNode.handlers.splice(index, 1)
    }
  }
}

// 获取审批数据
const getApprovalData = () => {
  // 获取转换后的人员配置数据
  const assigneeConfig = getAssigneeConfig()
  
  // 简化返回结果，只包含必要数据
  const result = {
    approvalForm: approvalForm.value,
    // 移除nextNodes，因为后端不需要
    // nextNodes: activeNextNodes.value,
    // 始终传递 assigneeConfig，让后端决定是否使用
    assigneeConfig: assigneeConfig
  }
  
  // 如果是转办，添加转办人员信息
  if (approvalForm.value.approvalResult === 'TRANSFER') {
    result.transferAssignee = transferAssignee.value
    result.transferAssigneeName = transferAssigneeName.value
  }
  
  return result
}

// 检查人员配置是否被修改过（已废弃，不再使用）
const checkPersonnelModified = () => {
  // 始终返回 true，表示始终传递 assigneeConfig
  return true
}

// 获取人员配置数据
const getAssigneeConfig = () => {
  const result = []
  
  // 处理所有节点
  activeNextNodes.value.forEach(node => {
    // 如果是网关节点，处理其分支节点
    if (isGatewayNode(node)) {
      processGatewayNode(node, result)
    } else {
      // 处理普通节点
      processNormalNode(node, result)
    }
  })
  
  return result
}

/**
 * 判断是否为网关节点
 * @param {Object} node - 节点对象
 * @returns {boolean} 是否为网关节点
 */
const isGatewayNode = (node) => {
  const nodeType = node.type || node.nodeType || ''
  return nodeType.includes('Gateway') || nodeType.includes('GATEWAY')
}

/**
 * 处理网关节点的人员配置
 * @param {Object} gatewayNode - 网关节点
 * @param {Array} result - 结果数组
 */
const processGatewayNode = (gatewayNode, result) => {
  if (!gatewayNode.gatewayBranches) return
  
  gatewayNode.gatewayBranches.forEach(branch => {
    if (branch.targetNodeInfo && isUserTaskNode(branch.targetNodeInfo)) {
      const targetNode = branch.targetNodeInfo
      const nodeConfig = createNodeConfig(targetNode)
      
      if (hasPersonnel(nodeConfig)) {
        result.push(nodeConfig)
      }
    }
  })
}

/**
 * 处理普通节点的人员配置
 * @param {Object} node - 普通节点
 * @param {Array} result - 结果数组
 */
const processNormalNode = (node, result) => {
  const nodeConfig = createNodeConfig(node)
  
  if (hasPersonnel(nodeConfig)) {
    result.push(nodeConfig)
  }
}

/**
 * 判断是否为用户任务节点
 * @param {Object} node - 节点对象
 * @returns {boolean} 是否为用户任务节点
 */
const isUserTaskNode = (node) => {
  const nodeType = node.nodeType || node.type || ''
  return nodeType === 'USER_TASK' || nodeType === 'UserTask' || nodeType === 'userTask'
}

/**
 * 获取节点的人员配置（优先使用用户修改后的配置）
 * @param {Object} node - 目标节点
 * @param {string} type - 配置类型：'handlers' | 'ccHandlers'
 * @returns {Array} 人员配置列表
 */
const getNodePersonnel = (node, type = 'handlers') => {
  const fieldName = type === 'handlers' ? 'convertedPersonnel' : 'convertedCcPersonnel'
  const fallbackField = type === 'handlers' ? 'handlers' : 'ccHandlers'
  
  // 优先使用用户修改后的配置，如果没有则使用原始配置
  return node[fieldName] || node[fallbackField] || []
}

/**
 * 创建节点配置对象
 * @param {Object} node - 节点对象
 * @returns {Object} 节点配置对象
 */
const createNodeConfig = (node) => {
  // 安全地获取 advanced 属性，避免 undefined 错误
  const nodeAdvanced = node.advanced || {}
  const nodeCountersign = node.countersign || {}
  
  return {
    id: node.id || node.nodeId,
    name: node.name || node.nodeName,
    type: node.type || node.nodeType,
    handlers: getNodePersonnel(node, 'handlers'),
    ccHandlers: getNodePersonnel(node, 'ccHandlers'),
    notificationMethods: node.notificationMethodsArray || ['system'],
    advanced: {
      personnelEditPermission: nodeAdvanced.personnelEditPermission || 'full',
      countersign: {
        type: nodeCountersign.type || '',
        completionType: nodeCountersign.completionType || 'all',
        minPass: nodeCountersign.minPass || null,
        maxPass: nodeCountersign.maxPass || null,
        percentage: nodeCountersign.percentage || 50
      }
    }
  }
}

/**
 * 检查节点是否有人员配置
 * @param {Object} nodeConfig - 节点配置对象
 * @returns {boolean} 是否有人员配置
 */
const hasPersonnel = (nodeConfig) => {
  return (nodeConfig.handlers && nodeConfig.handlers.length > 0) ||
         (nodeConfig.ccHandlers && nodeConfig.ccHandlers.length > 0)
}

// 转换assignees为具体人员列表
const convertAssigneesToPersonnel = (assignees) => {
  const personnel = []
  const processedIds = new Set()
  
  for (const assignee of assignees) {
    if (assignee.type === 'user' && assignee.value && Array.isArray(assignee.value)) {
      // 用户类型：直接添加用户ID
      for (const user of assignee.value) {
        if (user.id && !processedIds.has(user.id)) {
          processedIds.add(user.id)
          personnel.push({
            id: user.id,
            name: user.nickName || user.name,
            type: 'user'
          })
        }
      }
    }
  }
  
  return personnel
}

// 验证表单
const validateForm = async () => {
  try {
    await approvalFormRef.value.validate()
    return true
  } catch (error) {
    return false
  }
}

// 重置表单
const resetForm = () => {
  approvalFormRef.value.resetFields()
  approvalForm.value.approvalResult = 'PASS'
  approvalForm.value.approvalOpinion = ''
  nextNodes.value = []
  selectedNextNode.value = ''
  activeNextNodes.value = []
  emit('approval-change', approvalForm.value)
}

// 切换表单数据预览
const toggleFormDataPreview = () => {
  showFormDataPreview.value = !showFormDataPreview.value
  if (showFormDataPreview.value) {
    // 优先使用传入的 formData prop，然后尝试从其他来源获取
    let formData = props.formData || {}
    
    // 如果formData是包含formData字段的对象，则提取formData字段
    if (formData && typeof formData === 'object' && formData.formData) {
      formData = formData.formData
    }
    
    // 如果还是大对象，尝试从其他来源获取
    if (Object.keys(formData).length > 20) {
      // 尝试从processData或taskData中获取formData
      const processFormData = props.processData?.formData
      const taskFormData = props.taskData?.formData
      
      if (processFormData && typeof processFormData === 'object') {
        formData = processFormData.formData || processFormData
      } else if (taskFormData && typeof taskFormData === 'object') {
        formData = taskFormData.formData || taskFormData
      }
    }
    
    formDataPreview.value = formData
  } else {
    formDataPreview.value = {}
  }
}

// 计算网关条件是否满足
const evaluateCondition = (conditionExpression, formData) => {
  if (!conditionExpression || !formData) {
    return false
  }
  
  try {
    // 解析条件表达式
    let expression = conditionExpression.trim()
    
    // 处理常见的条件表达式格式
    if (expression.startsWith('${') && expression.endsWith('}')) {
      expression = expression.substring(2, expression.length - 1)
    }
    
    // 解析简单的比较表达式
    return parseSimpleExpression(expression, formData)
    
  } catch (error) {
    console.error('条件表达式计算失败:', conditionExpression, error)
    return false
  }
}

// 解析简单表达式
const parseSimpleExpression = (expression, formData) => {
  try {
    // 处理常见的比较操作符
    if (expression.includes('>=')) {
      return parseComparison(expression, '>=', formData)
    } else if (expression.includes('<=')) {
      return parseComparison(expression, '<=', formData)
    } else if (expression.includes('!=')) {
      return parseComparison(expression, '!=', formData)
    } else if (expression.includes('==')) {
      return parseComparison(expression, '==', formData)
    } else if (expression.includes('>')) {
      return parseComparison(expression, '>', formData)
    } else if (expression.includes('<')) {
      return parseComparison(expression, '<', formData)
    } else if (expression.includes('=')) {
      return parseComparison(expression, '=', formData)
    }
    
    // 处理布尔表达式
    if (expression.toLowerCase() === 'true') {
      return true
    } else if (expression.toLowerCase() === 'false') {
      return false
    }
    
    // 处理变量引用
    if (formData.hasOwnProperty(expression)) {
      const value = formData[expression]
      if (typeof value === 'boolean') {
        return value
      } else if (typeof value === 'string') {
        return value.trim() !== ''
      } else if (typeof value === 'number') {
        return value !== 0
      }
      return value != null
    }
    
    // 默认返回false
    return false
    
  } catch (error) {
    console.error('解析表达式失败:', expression, error)
    return false
  }
}

// 解析比较表达式
const parseComparison = (expression, operator, formData) => {
  try {
    const parts = expression.split(operator, 2)
    if (parts.length !== 2) {
      return false
    }
    
    const leftVar = parts[0].trim()
    const rightValue = parts[1].trim()
    
    // 获取左侧变量的值
    const leftValue = getVariableValue(leftVar, formData)
    
    if (leftValue === null || leftValue === undefined) {
      return false
    }
    
    // 解析右侧值
    const rightVal = parseValue(rightValue, formData)
    
    // 执行比较
    const result = compareValues(leftValue, rightVal, operator)
    return result
    
  } catch (error) {
    console.error('解析比较表达式失败:', expression, error)
    return false
  }
}

// 获取变量值
const getVariableValue = (variable, formData) => {
  // 移除可能的${}包装
  if (variable.startsWith('${') && variable.endsWith('}')) {
    variable = variable.substring(2, variable.length - 1)
  }
  
  // 支持嵌套属性访问，如 formData.amount
  if (variable.includes('.')) {
    const parts = variable.split('.')
    let current = formData
    for (const part of parts) {
      if (current && typeof current === 'object' && current.hasOwnProperty(part)) {
        current = current[part]
      } else {
        return null
      }
    }
    return current
  }
  
  return formData[variable]
}

// 解析值
const parseValue = (value, formData) => {
  value = value.trim()
  
  // 移除引号
  if ((value.startsWith('"') && value.endsWith('"')) || 
      (value.startsWith("'") && value.endsWith("'"))) {
    return value.substring(1, value.length - 1)
  }
  
  // 尝试解析为数字
  if (!isNaN(value)) {
    if (value.includes('.')) {
      return parseFloat(value)
    } else {
      return parseInt(value)
    }
  }
  
  // 不是数字，尝试作为变量处理
  return getVariableValue(value, formData)
}

// 比较值
const compareValues = (left, right, operator) => {
  try {
    // 如果都是数字类型
    if (typeof left === 'number' && typeof right === 'number') {
      switch (operator) {
        case '>': return left > right
        case '>=': return left >= right
        case '<': return left < right
        case '<=': return left <= right
        case '==': return left === right
        case '!=': return left !== right
        default: return false
      }
    }
    
    // 如果都是字符串类型
    if (typeof left === 'string' && typeof right === 'string') {
      switch (operator) {
        case '==': return left === right
        case '!=': return left !== right
        default: return false
      }
    }
    
    // 其他情况，转换为字符串比较
    const leftStr = String(left)
    const rightStr = String(right)
    
    switch (operator) {
      case '==': return leftStr === rightStr
      case '!=': return leftStr !== rightStr
      default: return false
    }
    
  } catch (error) {
    console.error('比较值失败:', left, operator, right, error)
    return false
  }
}

// 更新网关分支条件状态
const updateGatewayConditions = () => {
  // 获取表单数据，优先从formData prop获取，然后从其他来源获取
  let currentFormData = props.formData || {}
  
  // 如果formData是包含formData字段的对象，则提取formData字段
  if (currentFormData && typeof currentFormData === 'object' && currentFormData.formData) {
    currentFormData = currentFormData.formData
  }
  
  // 如果还是大对象，尝试从其他来源获取
  if (Object.keys(currentFormData).length > 20) {
    const processFormData = props.processData?.formData
    const taskFormData = props.taskData?.formData
    
    if (processFormData && typeof processFormData === 'object') {
      currentFormData = processFormData.formData || processFormData
    } else if (taskFormData && typeof taskFormData === 'object') {
      currentFormData = taskFormData.formData || taskFormData
    }
  }
  
  // 使用setTimeout避免在响应式更新过程中修改数据
  setTimeout(() => {
    try {
      // 遍历所有下一节点，更新网关分支的条件状态
      nextNodes.value.forEach(node => {
        if (node.gatewayBranches && node.gatewayBranches.length > 0) {
          node.gatewayBranches.forEach(branch => {
            if (branch.conditionExpression) {
              const conditionMet = evaluateCondition(branch.conditionExpression, currentFormData)
              // 使用Object.assign避免直接修改响应式数据
              Object.assign(branch, { conditionMet })
            }
          })
        }
      })
    } catch (error) {
      console.error('更新网关条件失败:', error)
    }
  }, 0)
}

// 处理节点处理人员变化
const onNodeAssigneesChange = (node) => {
  // 这里可以添加额外的处理逻辑，比如验证、格式化等
  // 人员列表会自动更新，因为PersonnelList组件监听了assignees的变化
}

// 处理节点抄送人员变化
const onNodeCcAssigneesChange = (node, ccAssignees) => {
  node.ccAssignees = ccAssignees
}

// 处理通知方式变化
const onNotificationMethodsChange = (node, methods) => {
  node.notificationMethodsArray = methods
}

// 查看人员详情
const viewPersonnelDetail = (person) => {
  // 这里可以打开一个模态框或弹窗，展示人员详情
  ElMessage.info(`查看人员详情: ${person.name} (${person.account})`)
}

// 更新节点处理人员
const updateNodePersonnel = (node, personnel, type = 'handlers') => {
  const nodeId = node.id || node.nodeId
  const fieldName = type === 'handlers' ? 'convertedPersonnel' : 'convertedCcPersonnel'
  
  // 更新对应字段
  node[fieldName] = personnel
}

// 更新节点抄送人员
const updateNodeCcPersonnel = (node, personnel) => {
  // 使用统一的更新方法
  updateNodePersonnel(node, personnel, 'ccHandlers')
}

// 将handlers格式转换为assignees格式（用于网关分支）
const convertHandlersToAssigneesForBranch = (handlers) => {
  // 使用统一的转换方法
  return convertHandlersToAssignees(handlers)
}

// 更新网关分支处理人员
const updateBranchHandlers = (branch, assignees) => {
  // 使用统一的更新方法
  updateBranchPersonnel(branch, assignees, 'handlers')
}

// 更新网关分支抄送人员
const updateBranchCcHandlers = (branch, ccAssignees) => {
  // 使用统一的更新方法
  updateBranchPersonnel(branch, ccAssignees, 'ccHandlers')
}

// 更新网关分支通知方式
const updateBranchNotificationMethods = (branch, notificationMethods) => {
  const branchId = branch.targetNodeId
  
  // 查找目标节点
  let targetNode = findTargetNode(branch)
  
  if (targetNode) {
    // 更新通知方式
    targetNode.notificationMethodsArray = notificationMethods
  }
  
  // 同时更新 branch.targetNodeInfo 中的配置，确保 getAssigneeConfig 能获取到
  if (branch.targetNodeInfo) {
    branch.targetNodeInfo.notificationMethodsArray = notificationMethods
  }
}

// 更新网关分支人员详情
const updateBranchPersonnel = (branch, personnel, type = 'handlers') => {
  const branchId = branch.targetNodeId
  const fieldName = type === 'handlers' ? 'convertedPersonnel' : 'convertedCcPersonnel'
  
  // 查找目标节点
  let targetNode = findTargetNode(branch)
  
  if (targetNode) {
    // 更新人员配置
    targetNode[fieldName] = personnel
  }
  
  // 同时更新 branch.targetNodeInfo 中的配置，确保 getAssigneeConfig 能获取到
  if (branch.targetNodeInfo) {
    branch.targetNodeInfo[fieldName] = personnel
  }
}

// 更新网关分支抄送人员详情
const updateBranchCcPersonnel = (branch, personnel) => {
  // 使用统一的更新方法
  updateBranchPersonnel(branch, personnel, 'ccHandlers')
}

// 组件挂载时加载下一节点配置
onMounted(() => {
  // 下一节点数据现在从props接收，不需要手动加载
})

// 监听流程数据变化
// watch(() => props.graphData, () => {
//   // 流程数据变化时更新网关条件状态
//   updateGatewayConditions()
// }, { deep: true })

// 监听表单数据变化，实时更新网关条件状态
// watch(() => props.formData, () => {
//   updateGatewayConditions()
// }, { deep: true })

// 移除可能导致循环的watch监听器
// 监听流程数据中的表单数据变化
// watch(() => props.processData?.formData, () => {
//   updateGatewayConditions()
// }, { deep: true })

// 监听任务数据中的表单数据变化
// watch(() => props.taskData?.formData, () => {
//   updateGatewayConditions()
// }, { deep: true })

// 移除nextNodes.value的watch监听器，避免循环更新
// watch(() => nextNodes.value, () => {
//   updateGatewayConditions()
// }, { deep: true })

// 获取网关条件数据，用于流程图样式显示
const getGatewayConditions = () => {
  // 获取表单数据
  const formData = props.formData || {}
  let currentFormData = formData
  
  // 如果formData是包含formData字段的对象，则提取formData字段
  if (currentFormData && typeof currentFormData === 'object' && currentFormData.formData) {
    currentFormData = currentFormData.formData
  }
  
  // 使用公共方法计算网关条件
  const gatewayConditions = calculateGatewayConditions(activeNextNodes.value, currentFormData)
  
  return gatewayConditions
}

// 暴露方法给父组件
defineExpose({
  getApprovalData,
  validateForm,
  getAssigneeConfig: () => {
    const assigneeConfig = []
    
    // 处理所有节点，包括网关分支节点
    activeNextNodes.value.forEach(node => {
      // 如果是网关节点，需要处理其分支节点
      if ((node.type && node.type.includes('Gateway')) || (node.nodeType && node.nodeType.includes('GATEWAY'))) {
        // 处理网关分支节点
        if (node.gatewayBranches && node.gatewayBranches.length > 0) {
          node.gatewayBranches.forEach(branch => {
            
            // 处理分支目标节点
            if (branch.targetNodeInfo) {
              const targetNode = branch.targetNodeInfo
              
              // 如果是用户任务节点，需要处理其人员配置
              if (targetNode.nodeType === 'USER_TASK' || targetNode.nodeType === 'UserTask' || targetNode.nodeType === 'userTask') {
                // 获取处理人员配置 - 修复数据源优先级
                // 优先使用 convertedPersonnel（用户修改后的数据）
                // 如果没有 convertedPersonnel，则使用 handlers（原始数据）
                const handlers = targetNode.convertedPersonnel || targetNode.handlers || []
                const ccHandlers = targetNode.convertedCcPersonnel || targetNode.ccHandlers || []
                
                // 只要有处理人员或抄送人员就添加到配置中
                if (handlers.length > 0 || ccHandlers.length > 0) {
                  assigneeConfig.push({
                    id: targetNode.nodeId,
                    name: targetNode.nodeName,
                    type: targetNode.nodeType,
                    handlers: handlers,
                    ccHandlers: ccHandlers,
                    notificationMethods: targetNode.notificationMethodsArray || ['system']
                  })
                }
              }
            }
          })
        }
      } else {
        // 处理普通节点（非网关节点）
        // 优先使用convertedPersonnel（SimplePersonnelList转换后的数据）
        // 如果没有convertedPersonnel，则使用handlers
        const handlers = node.convertedPersonnel || node.handlers || []
        
        // 优先使用convertedCcPersonnel（SimplePersonnelList转换后的数据）
        // 如果没有convertedCcPersonnel，则使用ccAssignees
        const ccHandlers = node.convertedCcPersonnel || node.ccAssignees || []
        
        // 只要有处理人员或抄送人员就添加到配置中
        if (handlers.length > 0 || ccHandlers.length > 0) {
          assigneeConfig.push({
            id: node.id || node.nodeId,
            name: node.name || node.nodeName,
            type: node.type || node.nodeType,
            handlers: handlers, // 返回handlers格式，而不是assignees
            ccHandlers: ccHandlers, // 抄送人员配置
            notificationMethods: node.notificationMethodsArray || ['system'] // 通知方式
          })
        }
      }
    })
    
    return assigneeConfig
  },
  getGatewayConditions
})

// 显示转办人员选择器
const showTransferSelector = () => {
  transferSelectorVisible.value = true
}

// 清空转办人员
const clearTransferAssignee = () => {
  transferAssignee.value = ''
  transferAssigneeName.value = ''
  transferForm.value.transferAssignee = ''
}

// 处理转办人员选择
const handleTransferAssigneeSelect = (users) => {
  if (users && users.length > 0) {
    const user = users[0]
    transferAssignee.value = user.id || user.userId
    transferAssigneeName.value = user.nickName || user.name || user.userName
    transferForm.value.transferAssignee = transferAssignee.value
  }
  transferSelectorVisible.value = false
}

// 表单数据（用于发起流程时传递）
const formData = ref({})

// 监听 props.formData 变化
watch(() => props.formData, (newFormData) => {
  if (newFormData) {
    formData.value = newFormData.formData || newFormData
  }
}, { immediate: true, deep: true })

// 处理人员配置展开状态变化
const onHandlerConfigCollapsedChange = (node, collapsed) => {
  node.handlerConfigCollapsed = collapsed
}

// 处理抄送配置展开状态变化
const onCcConfigCollapsedChange = (node, collapsed) => {
  node.ccConfigCollapsed = collapsed
}

// 查找网关分支的目标节点
const findTargetNode = (branch) => {
  // 优先通过 targetNodeId 查找
  let targetNode = activeNextNodes.value.find(node => 
    (node.id || node.nodeId) === branch.targetNodeId
  )
  
  // 如果没找到，尝试通过 targetNodeInfo.nodeId 查找
  if (!targetNode && branch.targetNodeInfo) {
    targetNode = activeNextNodes.value.find(node => 
      (node.id || node.nodeId) === branch.targetNodeInfo.nodeId
    )
  }
  
  return targetNode
}
</script>

<style scoped>
.approval-operation {
  padding: 20px 0;
}

.approval-basic-section,
.next-node-config-section,
.cc-config-section,
.submit-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.subsection-title {
  margin: 0 0 15px 0;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}

.sub-subsection-title {
  margin: 0 0 10px 0;
  font-size: 13px;
  font-weight: 500;
  color: #606266;
}

.config-content {
  padding: 0;
}

.node-selection {
  margin-bottom: 20px;
}

.node-config {
  margin-bottom: 20px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.handler-config,
.cc-config {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid #e8eaec;
  border-radius: 4px;
  background: #fafbfc;
}

.selected-handlers,
.selected-cc {
  margin-bottom: 15px;
  min-height: 40px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fafafa;
}

.handler-tag,
.cc-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.selected-cc-user {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  margin-bottom: 8px;
  background-color: #fafafa;
}

.selected-cc-user-info {
  flex-grow: 1;
  margin-left: 10px;
  margin-right: 10px;
}

.selected-cc-user-name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
  display: block;
}

.selected-cc-user-account {
  font-size: 12px;
  color: #909399;
  display: block;
  margin-top: 2px;
}

.selected-cc-user-remove {
  color: #f56c6c;
  font-size: 18px;
  padding: 0 5px;
  border: none;
  background-color: transparent;
  cursor: pointer;
}

.selected-cc-user-remove:hover {
  color: #f78989;
}

.no-cc-users {
  text-align: center;
  padding: 20px;
  color: #909399;
  font-size: 14px;
}

.add-handler,
.add-cc {
  margin-bottom: 15px;
}

.gateway-info,
.end-node-info {
  margin-bottom: 15px;
}

.gateway-branches {
  margin-top: 15px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #f8f9fa;
}

.branch-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.branch-item {
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
}

.branch-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.branch-name {
  font-weight: 500;
  color: #303133;
}

.branch-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.branch-target {
  display: flex;
  align-items: center;
  gap: 8px;
}

.branch-condition {
  padding: 6px 10px;
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #409eff;
}

.target-node-info {
  margin-top: 10px;
  padding: 10px;
  background: #fafafa;
  border-radius: 4px;
}

.target-node-description {
  margin-bottom: 8px;
}

.target-handlers {
  margin-top: 8px;
}

.handler-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-top: 4px;
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.el-checkbox {
  margin-right: 0;
}

.submit-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
  text-align: center;
}

.submit-section .el-button {
  margin: 0 10px;
  min-width: 120px;
}

.submit-section .el-button--primary {
  background: #409eff;
  border-color: #409eff;
}

.submit-section .el-button--primary:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}

.submit-section .el-button--primary:disabled {
  background: #c0c4cc;
  border-color: #c0c4cc;
  color: #fff;
}

.form-data-preview-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
}

.form-data-preview {
  background: #fafafa;
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  color: #303133;
  white-space: pre-wrap; /* 保留换行 */
  word-break: break-all; /* 允许单词断行 */
  overflow-x: auto; /* 允许横向滚动 */
}

.form-data-preview-button {
  text-align: center;
  margin-bottom: 30px;
}

.config-section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.config-actions {
  display: flex;
  gap: 8px;
}

.toggle-config-btn {
  color: #606266;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.toggle-config-btn:hover {
  color: #409eff;
  background: #f0f9ff;
}

.config-details {
  margin-top: 12px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
}

.notification-methods {
  margin-top: 12px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
}

/* 转办配置样式 */
.transfer-config-section {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fafafa;
}

.transfer-assignee-selector {
  display: flex;
  align-items: center;
}
</style> 